<template>
  <div>
    <el-button type="primary" @click="openDialog()">新增房屋</el-button>
    <el-table :data="tableData" style="width: 100%; margin-top: 16px">
      <el-table-column type="index" :index="(index) => index + 1" label="编号" width="80" />
      <el-table-column prop="bname" label="楼栋" />
      <el-table-column prop="hnum" label="房号" />
      <el-table-column prop="hsize" label="面积(㎡)" />
      <el-table-column prop="htype" label="户型" />
      <el-table-column prop="ibName" label="业主" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="openDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 16px"
      background
      layout="prev, pager, next, jumper, ->, total"
      :total="total"
      :page-size="pageSize"
      :current-page="currentPage"
      @current-change="handlePageChange"
    />
    <el-dialog :title="dialogTitle" v-model="dialogVisible">
      <el-form :model="form" label-width="90px">
        <el-form-item label="楼栋ID">
          <el-select v-model="form.bid" placeholder="请选择楼栋" @change="handleBuildingChange" clearable :disabled="buildingsLoading">
            <el-option v-for="building in buildings" :key="building.bid" :label="building.bname" :value="building.bid" />
          </el-select>
          <div v-if="buildingsLoading" class="el-loading-text">加载中...</div>
          <div v-if="buildingsError" class="text-danger">{{ buildingsError }}</div>
        </el-form-item>
        <el-form-item label="房号">
          <el-input v-model="form.hnum" />
        </el-form-item>
        <el-form-item label="面积(㎡)">
          <el-input v-model="form.hsize" />
        </el-form-item>
        <el-form-item label="户型">
          <el-input v-model="form.htype" />
        </el-form-item>
        <el-form-item label="业主">
          <el-select v-model="form.ibId" placeholder="请选择业主" @change="handleOwnerChange" clearable :disabled="residentsLoading">
            <el-option v-for="resident in residents" :key="resident.ibId" :label="`${resident.ibName}`" :value="resident.ibId" />
          </el-select>
          <div v-if="residentsLoading" class="el-loading-text">加载中...</div>
          <div v-if="residentsError" class="text-danger">{{ residentsError }}</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessageBox } from 'element-plus';
import {  postRequest, putRequest, deleteRequest, getRequest } from '@/utils/request';
const tableData = ref([]);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
const dialogVisible = ref(false);
const dialogTitle = ref('新增房屋');
const form = reactive({
  id: null,
  bname: '',
  bid: '',
  hnum: '',
  hsize: '',
  htype: '',
  ibName: '',
  ibId: ''
});
const buildings = ref([]);
const residents = ref([]);
const buildingsLoading = ref(false);
const residentsLoading = ref(false);
const buildingsError = ref('');
const residentsError = ref('');

function fetchData() {
  postRequest('/house/getHouseByPage', { current: currentPage.value, size: pageSize.value }).then(res => {
    if (res && res.data) {
      tableData.value = Array.isArray(res.data.data.houses) ? res.data.data.houses : [];
      total.value = res.data.data.total || 0;
    } else {
      tableData.value = [];
      total.value = 0;
    }
  }).catch(error => {
    console.error('获取数据失败:', error);
    tableData.value = [];
    total.value = 0;
  });
}

function fetchBuildings() {
  buildingsLoading.value = true;
  buildingsError.value = '';
  getRequest('/building/getBuildingList').then(res => {
    console.log('楼栋数据API完整响应:', res);
    if (res && res.data && Array.isArray(res.data.data)) {
      console.log('原始楼栋数据:', res.data.data);
      const validBuildings = res.data.data
        .filter(element => element && element.id !== undefined)
        .map(element => {
          // 详细日志记录名称字段选择过程
          let buildingName = element.name || element.bname || element.blName || element.buildingName;
          console.log(`楼栋ID: ${element.id}, 名称字段映射: name=${element.name}, bname=${element.bname}, blName=${element.blName}, 最终选择: ${buildingName}`);
          return {
            bid: String(element.id),
            bname: buildingName || `楼栋${element.id}`
          };
        });
      console.log('转换后的楼栋列表:', validBuildings);
      buildings.value = validBuildings;
      if (validBuildings.length === 0) {
        buildingsError.value = '未找到楼栋数据，请联系系统管理员';
      }
    } else {
      buildingsError.value = '楼栋数据格式不正确';
      console.error('楼栋数据格式错误:', res);
    }
  }).catch(error => {
    buildingsError.value = '获取楼栋列表失败: ' + (error.message || '网络错误');
    console.error('获取楼栋列表失败:', error);
  }).finally(() => {
    buildingsLoading.value = false;
  });
}

function fetchResidents() {
  residentsLoading.value = true;
  residentsError.value = '';
  getRequest('/inhabitants/getInhabitantsList').then(res => {
    console.log('业主数据API完整响应:', res);
    if (res && res.data && Array.isArray(res.data.data)) {
      console.log('原始业主数据:', res.data.data);
      const validResidents = res.data.data
        .filter(element => element && element.id !== undefined)
        .map(element => {
          // 详细日志记录名称字段选择过程
          let residentName = element.username || element.ibName || element.name || element.ib_username || element.inhabitantName;
          console.log(`业主ID: ${element.id}, 名称字段映射: username=${element.username}, ibName=${element.ibName}, name=${element.name}, 最终选择: ${residentName}`);
          return {
            ibId: String(element.id),
            ibName: residentName || `业主${element.id}`
          };
        });
      console.log('转换后的业主列表:', validResidents);
      residents.value = validResidents;
      if (validResidents.length === 0) {
        residentsError.value = '未找到业主数据，请联系系统管理员';
      }
    } else {
      residentsError.value = '业主数据格式不正确';
      console.error('业主数据格式错误:', res);
    }
  }).catch(error => {
    residentsError.value = '获取业主列表失败: ' + (error.message || '网络错误');
    console.error('获取业主列表失败:', error);
  }).finally(() => {
    residentsLoading.value = false;
  });
}

function openDialog(row) {
  if (row) {
    dialogTitle.value = '编辑房屋';
    console.log('编辑模式行数据完整信息:', row);
    Object.assign(form, row);
    // 详细日志记录ID字段映射过程
    console.log('行数据中的bid:', row.bid, '类型:', typeof row.bid);
    console.log('行数据中的bname:', row.bname, '类型:', typeof row.bname);
    console.log('行数据中的ibId:', row.ibId, '类型:', typeof row.ibId);
    console.log('行数据中的ibName:', row.ibName, '类型:', typeof row.ibName);
    // 强制转换为字符串类型，确保类型一致
    form.bid = String(row.bid !== undefined ? row.bid : row.bname || '');
    form.ibId = String(row.ibId !== undefined ? row.ibId : row.ibName || '');
    console.log('设置后的form.bid:', form.bid, '类型:', typeof form.bid);
    console.log('设置后的form.ibId:', form.ibId, '类型:', typeof form.ibId);
    // 手动触发变更事件以更新显示名称
    handleBuildingChange(form.bid);
    handleOwnerChange(form.ibId);
  } else {
    dialogTitle.value = '新增房屋';
    form.id = null;
    form.bid = '';
    form.bname = '';
    form.hnum = '';
    form.hsize = '';
    form.htype = '';
    form.ibId = '';
    form.ibName = '';
  }
  dialogVisible.value = true;
}

function handleBuildingChange(bid) {
  console.log('选中的楼栋ID:', bid, '类型:', typeof bid);
  // 确保比较时类型一致，将bid转换为字符串
  const selectedBuilding = buildings.value.find(building => building.bid === String(bid));
  console.log('找到的楼栋信息:', selectedBuilding);
  if (selectedBuilding) {
    form.bname = selectedBuilding.bname;
  } else {
    form.bname = '';
    console.warn('未找到ID为', bid, '的楼栋');
  }
}

function handleOwnerChange(ibId) {
  console.log('选中的业主ID:', ibId, '类型:', typeof ibId);
  // 确保比较时类型一致，将ibId转换为字符串
  const selectedResident = residents.value.find(resident => resident.ibId === String(ibId));
  console.log('找到的业主信息:', selectedResident);
  if (selectedResident) {
    form.ibName = selectedResident.ibName;
  } else {
    form.ibName = '';
    console.warn('未找到ID为', ibId, '的业主');
  }
}

function handleSubmit() {
  if (form.id) {
    putRequest('/house/updateHouseById', form).then(() => {
      dialogVisible.value = false;
      fetchData();
    });
  } else {
    postRequest('/house/addHouse', form).then(() => {
      dialogVisible.value = false;
      fetchData();
    });
  }
}

function handleDelete(id) {
  ElMessageBox.confirm('确定要删除该记录吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteRequest(`/house/deleteHouseById/${id}`).then(() => {
      fetchData();
    });
  }).catch(() => {});
}

function handlePageChange(page) {
  currentPage.value = page;
  fetchData();
}

onMounted(() => {
  fetchData();
  fetchBuildings();
  fetchResidents();
});
</script>